﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Microsoft.SharePoint;

namespace Inline.SharePoint.ExtendedVariations.Helpers
{

    class EventRegistrationHandler
    {

        private const string _assembly = "Inline.SharePoint.ExtendedVariations, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9bffad9fe6758fce";
        private Hashtable _eventTypeClassRelation = new Hashtable();

        public string Assembly { get { return _assembly; } }
        public Hashtable EventTypeClassRelation { get { return _eventTypeClassRelation; } }

        public EventRegistrationHandler()
        {

            _eventTypeClassRelation.Add(SPEventReceiverType.FieldAdded, "Inline.SharePoint.ExtendedVariations.Events.FieldAddedEventHandler");
            _eventTypeClassRelation.Add(SPEventReceiverType.FieldUpdated, "Inline.SharePoint.ExtendedVariations.Events.FieldUpdatedEventHandler");
            _eventTypeClassRelation.Add(SPEventReceiverType.FieldDeleting, "Inline.SharePoint.ExtendedVariations.Events.FieldDeletingEventHandler");
            _eventTypeClassRelation.Add(SPEventReceiverType.ItemAdded, "Inline.SharePoint.ExtendedVariations.Events.ItemAddedEventHandler");
            _eventTypeClassRelation.Add(SPEventReceiverType.ItemUpdated, "Inline.SharePoint.ExtendedVariations.Events.ItemUpdatedEventHandler");
            _eventTypeClassRelation.Add(SPEventReceiverType.ItemDeleting, "Inline.SharePoint.ExtendedVariations.Events.ItemDeletingEventHandler");

        }

        public bool ListAlreadyHasEventReceiverRegistered(SPList list, SPEventReceiverType rType, string className)
        {

            SPEventReceiverDefinitionCollection erdColl = list.EventReceivers;
            for (int i = 0; i < erdColl.Count; i++)
            {

                if (erdColl[i].Type == rType && erdColl[i].Assembly == _assembly && erdColl[i].Class == className)
                    return true;

            }

            return false;

        }

        public void DeleteRegisteredEventReceiver(SPList list, SPEventReceiverType rType, string className)
        {

            SPEventReceiverDefinitionCollection erdColl = list.EventReceivers;
            for (int i = erdColl.Count - 1; i > -1; i--)
            {

                if (erdColl[i].Type == rType && erdColl[i].Assembly == _assembly && erdColl[i].Class == className)
                    erdColl[i].Delete();

            }

            list.Update();

        }

    }

}